#include "filewriter.h"
#include <QDebug>
#include <QCoreApplication>
#include <QDir>
#include <QDateTime>

FileWriter::FileWriter(QObject *parent)
    : QThread(parent)
{
    QString timeStr1 = QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz");
    QString exeDir = QCoreApplication::applicationDirPath();
    QString filePath = exeDir + "/" + timeStr1 + ".264";
    m_file.setFileName(filePath);
    if (!m_file.open(QIODevice::WriteOnly))
    {
        qWarning() << "Failed to open output file";
    }
}

FileWriter::~FileWriter()
{
    stopWriting();
    m_file.close();
}

void FileWriter::enqueueNalu(const QByteArray &nalu)
{
    qInfo() << "enqueueNalu";

    QMutexLocker locker(&m_queueMutex);
    m_naluQueue.enqueue(nalu);
}

void FileWriter::stopWriting()
{
    m_running = false;
    wait();
}

void FileWriter::run()
{
    while (m_running || !m_naluQueue.isEmpty())
    {
        if (!m_naluQueue.isEmpty())
        {
            QMutexLocker locker(&m_queueMutex);
            QByteArray nalu = m_naluQueue.dequeue();
            locker.unlock();

            m_file.write("\x00\x00\x00\x01", 4); // Start code
            m_file.write(nalu);
            m_file.flush();
        } else {
            msleep(10); // 避免空转消耗CPU
        }
    }
}
